package com.example.easybuy.service.impl;

import com.example.easybuy.entity.*;
import com.example.easybuy.mappers.OrderMapper;
import com.example.easybuy.service.OrderService;
import com.example.easybuy.service.ProductService;
import com.example.easybuy.util.AjaxResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ProductService productService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public PageInfo<Order> orderByPage(Map<String, Object> map) {
        map.put("orderBy", "createTime desc");
        PageHelper.startPage(map);
        List<Order> list = orderMapper.orderByPage(map);
        return new PageInfo<>(list);
    }

    @Override
    public List<OrderDetail> selectOrderDetail(Map<String, Object> map) {
        return orderMapper.selectOrderDetail(map);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateOrder(Map<String, Object> map) throws Exception {
        if (map.containsKey("itStatus") && map.containsKey("orderId") && map.get("itStatus").toString().equals("3")) {
            String orderId = map.get("orderId").toString() + "-order";
            int id = Integer.parseInt(map.get("orderId").toString());
            Map<String, Object> updateProductMap = new HashMap<>();
            updateProductMap.put("orderId", id);
            List<OrderDetail> list = this.selectOrderDetail(updateProductMap);
            Product product;
            Map<String, Object> map1;//获取商品对象 更改库存
            try {
                for (OrderDetail OrderDetail : list) {
                    map1 = new HashMap<>();
                    map1.put("id", OrderDetail.getProductId());
                    product = productService.getPro(map1);
                    map1.put("stock", product.getStock() + OrderDetail.getQuantity());
                    map1.put("preStock", product.getPreStock() - OrderDetail.getQuantity());
                    productService.updatePro(map1, null);
                }
                stringRedisTemplate.delete(orderId);
            } catch (Exception e) {
                throw new Exception();
            }
        }
        return orderMapper.updateOrder(map) > 0;
    }

    @Override
    public boolean delOrder(Map<String, Object> map) {
        return orderMapper.delOrder(map) > 0;
    }

    @Override
    @Transactional
    public AjaxResult addOrder(List<CarDetail> list, String loginName, int userId, Address address) {
        ObjectMapper objectMapper = new ObjectMapper();
        Order order = new Order();
        order.setUserId(userId);
        order.setLoginName(loginName);
        order.setUserAddress(address.getProvince() + "省" + address.getCity() + "市" + address.getDistrict() + "区" + address.getDetailAddress());
        double totalPrice = 0;
        for (CarDetail carDetail : list) {
            totalPrice = totalPrice + carDetail.getTotalPrice();
        }
        order.setCost(totalPrice);
        order.setSerialNumber(UUID.randomUUID() + "");
        try {
            int orderAdd = orderMapper.addOrder(order);
            int id = order.getId();
            String orderJson = objectMapper.writeValueAsString(order);
            stringRedisTemplate.opsForValue().set(id + "-order", orderJson, 3, TimeUnit.MINUTES);
            OrderDetail orderDetail;
            for (CarDetail carDetail : list) {
                orderDetail = new OrderDetail();
                orderDetail.setCost(carDetail.getTotalPrice());
                orderDetail.setOrderId(id);
                orderDetail.setQuantity(carDetail.getTotalNum());
                orderDetail.setProductId(carDetail.getProductId());
                orderMapper.addOrderDetail(orderDetail);
            }
            if (orderAdd > 0) {
                Product product;
                Map<String, Object> map1;
                for (CarDetail carDetail : list) {
                    map1 = new HashMap<>();
                    map1.put("id", carDetail.getProductId());
                    product = productService.getPro(map1);
                    map1.put("stock", product.getStock() - carDetail.getTotalNum());
                    map1.put("preStock", carDetail.getTotalNum() + product.getPreStock());
                    productService.updatePro(map1, null);
                }
            }
            return AjaxResult.success().add("isAdd", orderAdd > 0).add("orderId", id);
        } catch (Exception e) {
            throw new RuntimeException("订单添加失败！", e);
        }
    }

    @Override
    public Order getOrder(Map<String, Object> map) {
        return orderMapper.getOrder(map);
    }
}
